
import { EXTENSION_PATH, exeCommand, AssetDB, findFile, FindFileType, copyDirectory, getGamePacks } from './utils';

const OS = require('os');
const FS = require('fs');
const Path = require('path');

const TAG = 'lcc-framework';

/**
 * 构建指定包声明
 * @param pack 
 */
async function buildPackDeclaration(pack:string){
	if(OS.platform() == "win32"){
		var command = "gulp buildDeclaration --pack " + pack;
		let result = await exeCommand(command, EXTENSION_PATH);
		if (result.error) {
			console.error('error : ' + result.error);
		}else{
			console.log(`${TAG} ${result.stdout}`);
			if(result.stderr){
				console.error(result.stderr);
			}
		}
	}
}

/**
 * 构建包声明
 */
async function buildDeclaration() {
    let decPacks = await Editor.Profile.getProject('lcc-framework', 'declaration.packs');
    let packs = getGamePacks().filter((pname)=>{ return decPacks[pname] });
	console.log(`${TAG} ${Editor.I18n.t("lcc-framework.build-begin")}`);
	for (let i = 0; i < packs.length; i++){
		console.log(`${TAG} ${Editor.I18n.t("lcc-framework.build-progress") + "(" + (i + 1) + "/" + packs.length + ") " + packs[i] + " ..."}`);
		await buildPackDeclaration(packs[i]); 
	}
    console.log(`${TAG} ${Editor.I18n.t("lcc-framework.build-end")}`);
}

/**
 * 导入框架
 */
function importFramework() {
	let sources = Path.join(EXTENSION_PATH, 'assets');
    let target = "db://assets/lcc-framework/";
    
	// 如果已经导入寻找目标目录
	let path = findFile(Path.join(Editor.Project.path, 'assets'), "lcc-framework", FindFileType.DIRECTORY);
	if(path){
		target = "db://" + path.substring(path.indexOf("assets")).replace("\\","/");
	}
    AssetDB.importAsset(sources, target, { overwrite : true });
	
    // 复制声明
    let srcpath = Path.join(EXTENSION_PATH, 'declarations');
    let decpath = Path.join(Editor.Project.path, '@types', 'lcc-framework');
    copyDirectory(srcpath, decpath);
}

/**
 * 插件加载回调
 */
export function load(){
	// 当 package 被正确加载的时候执行
	
}

/**
 * 插件卸载回调
 */
export function unload(){
	// 当 package 被正确卸载的时候执行
	
}

/**
 * 插件函数集合
 */
export namespace methods {
	/**
	 * 导入或更新框架
	 */
	export function import_framework(){
		importFramework();
	}

	/**
	 * 构建包声明
	 */
	export function build_pack_declarations(){
		buildDeclaration();
    }
    
    /**
     * 打开设置界面
     */
    export function open_settings_ui(){
        Editor.Panel.open('lcc-framework.settings');
    }
};
